﻿using ClientAppraise.Services;
using ClientAppraise.ViewModels.Validator;
using ClientAppraise.Views.Pages;
using ClientAppraise.Views.Pages.Users;
using ClientDao.User;
using ClientInfrastructure.Config;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using ShareCode.Dto;
using ShareCode.Dto.User;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Timers;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media.Imaging;

namespace ClientAppraise.ViewModels.Pages.Users
{
    public partial class LoginViewModel : MyObservableValidator
    {
        [ObservableProperty]
        [ServerError]
        [UserName]
        private string userName = "zhouxinadmin";
        [ObservableProperty]
        [NotifyDataErrorInfo]
        [ServerError]
        [UserName]
        private string password = "zhouxinadmin";
        [ObservableProperty]
        [NotifyDataErrorInfo]
        [ServerError]
        [ValidatorCode]
        private string verification = "";
        [ObservableProperty]
        private BitmapImage? imageVerificationCode;
        [ObservableProperty]
        private int verificationCodeTime = 30;
        [ObservableProperty]
        private bool rememberPassword;

        [RelayCommand]
        private void OnSubmit(LoginView window)
        {
            App.GetRequiredService<WindowsProviderService>()?.ShowAsMain<MainWindow>();


            //var asdf = window.aaa.GetBindingExpression(TextBox.TextProperty);
            //ValidateAllProperties(true);



            return;
            /*
            if (HasErrors)
            {
                return;
            }

            void fun(ResultDto<LoginReturnDto>? result, Exception? ex)
            {

                if (!App.Current.Dispatcher.CheckAccess())
                {
                    App.Current.Dispatcher.Invoke(() => fun(result, ex));
                    return;
                }

                if (ex != default)
                {
                    App.MySnackbar.Danger("服务器端错误", ex.Message, 9999999);
                    return;
                }

                if (result?.Success ?? false)
                {
                    timer.Stop();

                    MyAppContextModel.Obj.UserInfo = result.Data;

                    App.GetRequiredService<WindowsProviderService>()?.ShowAsMain<MainWindow>();
                    return;
                }

                //显示错误信息
                this.ServerErrors = result?.DetailMSg ?? [];
                ValidateAllPropertiesWithServer();

                if (!string.IsNullOrEmpty(result?.Message))
                {
                    App.MySnackbar.Danger("登录失败", result.Message);
                }
            }

            await App.MyContentDialog.ShowRingLoadingAsync(async () =>
            {
                try
                {
                    var result = await new UserAccountDal().LoginByNameAndPsw(new LoginByNameAndPswResqestDto
                    {
                        Password = this.Password,
                        UserName = this.UserName,
                        Verification = this.Verification,
                        SaveLoginState = RememberPassword ? 1 : 0
                    });

                    fun(result, null);

                }
                catch (Exception ex)
                {
                    fun(null, ex);
                }
                finally
                {
                    App.MyContentDialog.CloseLoading();
                }
            }, "正在登录");
            */
        }



        [RelayCommand]
        public async Task OnRefreshVerificationCodeAsync()
        {
            void fun(System.IO.Stream stream)
            {

                if (!App.Current.Dispatcher.CheckAccess())
                {
                    App.Current.Dispatcher.Invoke(() => fun(stream));
                    return;
                }

                var bitmap = new BitmapImage();

                bitmap.BeginInit();
                bitmap.StreamSource = stream;
                bitmap.EndInit();

                ImageVerificationCode = bitmap;
                VerificationCodeTime = 60;
                timer.Start();
            }

            timer.Stop();

            await App.MyContentDialog.ShowRingLoadingAsync(async () =>
            {
                try
                {
                    var a = await (new UserAccountDal()).GetVerificationCode(50, 170);
                    fun(a);
                }
                finally
                {
                    App.MyContentDialog.CloseLoading();
                }
            }, "正在获取验证码");
        }

        private readonly System.Timers.Timer timer;
        public LoginViewModel()
        {
            timer = new System.Timers.Timer(1000);
            timer.Elapsed += OnTimer_Elapsed;
        }

        private void OnTimer_Elapsed(object? sender, ElapsedEventArgs e)
        {
            VerificationCodeTime--;

            if (VerificationCodeTime < 1)
            {
                timer.Stop();
            }
            return;
        }
    }

}
